package com.rock.code.base.controller;

import com.alibaba.fastjson.JSONObject;
import com.rock.code.base.domain.AjaxJson;
import com.rock.code.base.domain.Constants;
import com.rock.code.system.user.domain.TbSysLoginmsg;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * The type Base controller.
 *
 * @author kongqiang
 * @date 2017.12.29
 */
public abstract class BaseController {

    /**
     * The Ajax json.
     */
    protected AjaxJson ajaxJson = new AjaxJson();

    /**
     * The Json.
     */
    protected JSONObject json = new JSONObject();

    /**
     * The Request.
     */
    protected HttpServletRequest request;
    /**
     * The Response.
     */
    protected HttpServletResponse response;
    /**
     * The Session.
     */
    protected HttpSession session;

    /**
     * Set req and res.
     *
     * @param request  the request
     * @param response the response
     * @author kongqiang
     * @date 2017.12.29
     */
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }

    /**
     * Gets request map single.
     *
     * @return the request map single
     * @author kongqiang
     * @date 2017.03.23
     */
    protected HashMap<String, Object> getRequestMapSingle() {
        HashMap<String, Object> conditions = new HashMap<String, Object>();
        Map map = request.getParameterMap();

        for (Object o : map.keySet()) {
            String key = (String) o;
            String[] values = (String[]) map.get(key);
            if (values.length > 1) {
                conditions.put(key, values);
            } else {
                conditions.put(key, values[0].trim());

            }
        }
        return conditions;
    }


    /**
     * Get parameter values.
     *
     * @param parameter the parameter
     * @return the string [ ]
     * @author kongqiang
     * @date 2018.01.02
     */
    protected String[] getParameterValues(String parameter) {
        return request.getParameterValues(parameter);
    }


    /**
     * Is not empty.
     *
     * @param str the str
     * @return the boolean
     * @author kongqiang
     * @date 2017.12.29
     */
    protected boolean isNotEmpty(String str) {
        if (str != null && !"".equals(str)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Gets session user.
     *
     * @return the session user
     * @author kongqiang
     * @date 2017.12.29
     */
    protected TbSysLoginmsg getSessionUser() {
        return (TbSysLoginmsg) session.getAttribute(Constants.SESSION_USER);
    }

}
